// 全局请求封装
// export const BASE_URL = "https://sit.lp.local.ejoydg.com/zx-low-code-api/"

let BASE_URL = ""
// uEnvDev
if (import.meta.env.VITE_APP_ENV === 'development') {
	// 本地代理
	// #ifdef H5
	BASE_URL = "/dev-api"
	// #endif
	// #ifndef H5
	BASE_URL = "https://sit.lp.local.ejoydg.com/zx-low-code-api/"
	// #endif
}
// uEnvProd
if (import.meta.env.VITE_APP_ENV === 'production') {
	// 发布
	// BASE_URL = "https://sit.lp.local.ejoydg.com/zx-low-code-api/"
	BASE_URL = "/lowcode-api/"
}
export { BASE_URL };


// 请求超出时间
const timeout = 5000

// 需要修改token，和根据实际修改请求头
const service = (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Blade-Auth': uni.getStorageSync('token') || '',
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': 'Bearer ' + uni.getStorageSync('token') || '',
		'Tenant-Id': uni.getStorageSync('tenantId') || 'xxx', // avue配置相关
		'isToken': true,
		...params.headers
	}
	if(header.isToken){
		if(!header['Blade-Auth']){
			setTimeout(() => {
				uni.navigateTo({
					url: "/pages/login/index",
				})
			}, 1000);
			uni.hideLoading();
			return
		}
	}
	
	// 处理接口第一个字符是否斜杆问题
	let urlHandle = url.startsWith("/") ? url : "/" + url
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + urlHandle, // 非H5端即微信小程序或App
			method: method,
			header: header,
			data: data,
			timeout,
			success(response) {
				const res = response
				// 根据返回的状态码做出对应的操作
				//获取成功
				// console.log(res)
				if (res.data.code == 200) {
					resolve(res.data.data);
				} else {
					uni.clearStorageSync()
					switch (res.data.code) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/login/index",
										})
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						default:
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
				// uni.hideToast();
			}
		});
	}).catch(() => {});
};

export default service
